<template>
    <el-dialog v-model="visible" title="发布攻略" width="60%" align-center :close-on-click-modal="false" @close="exit">
        <el-steps :active="active" finish-status="success" align-center :style="{ marginBottom: '20px' }">
            <el-step title="编辑标题" />
            <el-step title="编辑正文" />
            <el-step title="上传封面" />
        </el-steps>
        <el-form :rules="rules" :model="form" ref="formRef" v-show="active === 0">
            <el-form-item label="标题" prop="title">
                <el-input v-model="form.title" placeholder="请输入攻略的标题" />
            </el-form-item>
            <el-form-item label="描述" prop="detail">
                <el-input v-model="form.detail" :rows="3" type="textarea" placeholder="来吧，尽情发挥吧..." />
            </el-form-item>
        </el-form>
        <div class="mgb20" ref="editor" :style="{ display: active === 1 ? 'block' : 'none' }"></div>
        <el-upload action="#" :auto-upload="false" drag multiple ref="uploadRef" :limit="1"
            :before-upload="beforeUpload" v-show="active === 2">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
                拖拽上传或者 <em>点击上传</em>
            </div>
            <template #tip>
                <div class="el-upload__tip">
                    请上传新闻封面图片
                </div>
            </template>
        </el-upload>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="active -= 1" :disabled="active <= 0" :loading="loading">上一步</el-button>
                <el-button @click="submit" v-if="active === 2">发布</el-button>
                <el-button @click="nextStep(formRef)" v-else>下一步</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import WangEditor from 'wangeditor';
import type { FormRules } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { reactive, ref, onBeforeUnmount, watch } from 'vue';
import { ElMessage } from 'element-plus'
import axios from '@/utils/request'


const emit = defineEmits(['refresh'])
const visible = ref(false);
const active = ref(0) //步骤条当前进度
const emitShow = () => {
    visible.value = true;
    formRef.value?.resetFields();
}
const nextStep = (form: any) => {
    form.validate((valid: boolean) => {
        if (!valid) return;
        active.value += 1;
    })
}
// 传递给父组件的方法
defineExpose({ emitShow })

const form = reactive({
    title: '',
    detail: ''
})

const loading = ref(false)
const formRef = ref(null as any)

const rules = reactive<FormRules>({
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 5, max: 31, message: '帖子标题为5-31字', trigger: 'blur' },
    ],
    detail: [
        { required: true, message: '请输入帖子描述', trigger: 'blur' },
        { min: 10, max: 255, message: '描述至少10字，至多255字', trigger: 'blur' },
    ],
})

// 富文本编辑器
const editor = ref(null);
const content = reactive({
    html: '',
    text: ''
});
let instance: any;
watch(() => active.value, (newVal, oldVal) => {
    if (instance) return;
    if (newVal === 1) {
        instance = new WangEditor(editor.value);
        instance.config.zIndex = 1;
        instance.create();
    }
})
onBeforeUnmount(() => {
    instance = null;
});
const uploadRef:any = ref(null)
// 上传图片加表单
const beforeUpload = (file: any) => {
    loading.value = true;
    content.html = instance.txt.html();
    const fd = new FormData();
    fd.append('file', file)
    fd.append('title', form.title)
    fd.append('outline', form.detail)
    fd.append('type', 'introduction')
    fd.append('content', content.html)
    axios.post('/article/add', fd, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }).then((res: any) => {
        if (res.code !== 200) return ElMessage.error('上传失败')
        ElMessage.success('成功')
        visible.value = false;
        emit('refresh');
        instance.txt.clear()
    }).finally(() => loading.value = false)
    return false;
}

// 退出函数，清空数据
const exit = () => {
    active.value = 0;
}
const submit = () => {
    uploadRef.value!.submit()
}
</script>

<style scoped lang="scss">
.hidden {
    display: none;
}

.show {
    display: block;
}
</style>